package com.appkubes.fintech.admin.application.user.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.appkubes.fintech.admin.application.mall.MallService;
import com.appkubes.fintech.admin.application.risk.data.boole.service.BooleRiskService;
import com.appkubes.fintech.admin.application.user.dao.*;
import com.appkubes.fintech.admin.application.user.entity.dto.*;
import com.appkubes.fintech.admin.application.user.entity.vo.UserApprovalVO;
import com.appkubes.fintech.admin.application.user.entity.vo.UserBaseInfoVO;
import com.appkubes.fintech.admin.application.user.service.UserBaseInfoService;
import com.appkubes.fintech.common.response.Response;
import com.appkubes.fintech.common.util.ConversionUtil;
import com.appkubes.fintech.core.po.*;
import com.appkubes.fintech.core.pojo.FintechCreditMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/*
 * 用户基本信息
 * @author    xqc
 * @date    2020/01/01 14:46:28
 */
@Service
@Slf4j
public class UserBaseInfoServiceImpl implements UserBaseInfoService {

    @Resource
    private UserBaseInfoDao userBaseInfoDao;
    @Resource
    private UserJobDao jobDao;
    @Resource
    private MallService mallService;
    @Resource
    private UserDao userDao;

    @Resource
    private AfuDao afuDao;

    @Resource
    private AfuAfruadDao afuAfruadDao;

    @Resource
    private UserPersonalDao personalDao;
    @Resource
    private UserContactDao userContactDao;
    @Resource
    private UserBankCardDao bankCardDao;
    @Resource
    private FintechCreditMapper creditMapper;
    @Resource
    private BooleRiskService booleRiskService;

    @Value("${view.image.domain}")
    private String domainUrl;

    @Override
    public PageInfo<UserBaseInfoDTO> queryPage(UserBaseInfoVO userBaseInfoVO) {
        Page page = PageHelper.startPage(userBaseInfoVO.getPage(), userBaseInfoVO.getPageSize());
        FintechUserBaseInfoExample example = new FintechUserBaseInfoExample();
        FintechUserBaseInfoExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(userBaseInfoVO.getPhone())) {
            criteria.andPhoneEqualTo(userBaseInfoVO.getPhone());
        }
        if (StringUtils.isNotBlank(userBaseInfoVO.getRealName())) {
            criteria.andRealNameLike("%" + userBaseInfoVO.getRealName() + "%");
        }
        List<FintechUserBaseInfo> fintechUserBaseInfoList = userBaseInfoDao.selectByExample(example);
        List<UserBaseInfoDTO> responseList = ConversionUtil.ofList(fintechUserBaseInfoList, UserBaseInfoDTO.class);

        return new PageInfo<UserBaseInfoDTO>(responseList);
    }


    /**
     * @Author: XQC 2020/1/4/17:14
     * @params:
     * @return:
     * @Description:认证用户查询
     **/
    @Override
    public PageInfo<UserBaseInfoDTO> queryAuthPage(UserBaseInfoVO userBaseInfoVO) {
        PageHelper.startPage(userBaseInfoVO.getPage(), userBaseInfoVO.getPageSize());
        List<UserBaseInfoDTO> fintechUserBaseInfoList = userBaseInfoDao.queryAuthPage(userBaseInfoVO);
        return new PageInfo<>(fintechUserBaseInfoList);
    }


    @Override
    public Response<UserBaseInfoDTO> getById(String id) {
        FintechUserBaseInfo fintechUserBaseInfo = userBaseInfoDao.selectByPrimaryKey(id);
        UserBaseInfoDTO userBaseInfoDTO = new UserBaseInfoDTO();
        BeanUtils.copyProperties(fintechUserBaseInfo, userBaseInfoDTO);
        return Response.success(userBaseInfoDTO);

    }


    @Override
    public Response<UserDTO> getAuthId(String id) {
        UserDTO user = new UserDTO();
        FintechUserBaseInfo fintechUserBaseInfo = userBaseInfoDao.selectByPrimaryKey(id);
        UserBaseInfoDTO baseInfoDTO = new UserBaseInfoDTO();
        BeanUtil.copyProperties(fintechUserBaseInfo, baseInfoDTO);

        FintechUserPersonal personal = personalDao.selectByPrimaryKey(id);
        if (personal == null) {
            personal = new FintechUserPersonal();
        }
        BeanUtil.copyProperties(personal, baseInfoDTO);


        //存进去的乘以100，取出来除以100
        FintechCredit fintechCredit = creditMapper.selectByPrimaryKey(id);
        if (fintechCredit != null) {
            baseInfoDTO.setCreditTotalAmt((int) (fintechCredit.getCreditAmount() * 0.01f));
        }
        FintechUser fintechUser = userDao.selectByPrimaryKey(id);
        if (fintechUser == null) {
            fintechUser = new FintechUser();
        }
        baseInfoDTO.setIsAllAuth(fintechUser.getIsAllCertificate());
        baseInfoDTO.setIsPhoneAuthentication(fintechUser.getIsBaseInfoCertificate().byteValue());
        baseInfoDTO.setIdcardStatus(fintechUser.getIsRealNameCertificate());
        baseInfoDTO.setPortraitStatus(fintechUser.getIsBankCardCertificate());

        baseInfoDTO.setCreateTime(fintechUserBaseInfo.getCreateTime());
        baseInfoDTO.setUpdateTime(fintechUserBaseInfo.getUpdateTime());
        baseInfoDTO.setSubAuthTime(personal.getCreateTime());
        baseInfoDTO.setAuthTime(personal.getUpdateTime());
        baseInfoDTO.setIdCardFrontView(domainUrl + personal.getIdcardFrontView());
        baseInfoDTO.setIdCradBackView(domainUrl + personal.getIdcardBackView());
        baseInfoDTO.setFaceImg(domainUrl + personal.getFaceImg());
        baseInfoDTO.setLivingType(fintechUserBaseInfo.getLivingType());
        baseInfoDTO.setHousing(fintechUserBaseInfo.getHousing());
        baseInfoDTO.setSubAuthTime(fintechUser.getIsAllCertificateEndTime());
        baseInfoDTO.setAuthTime(fintechCredit.getHandlerTime());
        user.setBaseInfo(baseInfoDTO);

        FintechUserJob jobList = jobDao.selectByPrimaryKey(id);
        if (jobList == null) {
            jobList = new FintechUserJob();
        }
        UserJobDTO jobDTO = new UserJobDTO();
        BeanUtils.copyProperties(jobList, jobDTO);
        user.setJobList(jobDTO);

        FintechUserContactExample contactExample = new FintechUserContactExample();
        contactExample.createCriteria().andUserKeyEqualTo(id);
        List<FintechUserContact> contactList = userContactDao.selectByExample(contactExample);
        List<UserContractDTO> contactDtoList = ConversionUtil.ofList(contactList, UserContractDTO.class);
        user.setContactList(contactDtoList);


        FintechUserBankCard cardList = bankCardDao.selectByPrimaryKey(id);
        if (cardList == null) {
            cardList = new FintechUserBankCard();
        }
        UserBankCardDTO cardDtoList = new UserBankCardDTO();
        BeanUtils.copyProperties(cardList, cardDtoList);
        user.setCardList(cardDtoList);


        try {
            FintechDataAfuExample fintechDataAfuExample = new FintechDataAfuExample();
            fintechDataAfuExample.createCriteria().andUserKeyEqualTo(id);
            FintechDataAfu a = afuDao.selectByExample(fintechDataAfuExample).get(0);
            if ("0".equals(a.getDecisionSuggest())) {
                a.setDecisionSuggest("数据不足暂无评分");
            } else if ("1".equals(a.getDecisionSuggest())) {
                a.setDecisionSuggest("A-资质良好通过");
            } else if ("2".equals(a.getDecisionSuggest())) {
                a.setDecisionSuggest("B-资质尚可，审核后无风险通过");
            } else if ("3".equals(a.getDecisionSuggest())) {
                a.setDecisionSuggest("C-资质一般，正常审核");
            } else if ("4".equals(a.getDecisionSuggest())) {
                a.setDecisionSuggest("D-存在一定风险，严格审核");
            } else if ("5".equals(a.getDecisionSuggest())) {
                a.setDecisionSuggest("E-资质较差拒绝");
            }
            user.setAfu(a);
        } catch (Exception e) {
            e.printStackTrace();
        }

       /* try {
            FintechDataAfuFruadExample fintechDataAfuFruadExample = new FintechDataAfuFruadExample();
            fintechDataAfuFruadExample.createCriteria().andUserKeyEqualTo(id);
            List<FintechDataAfuFruad> list = afuAfruadDao.selectByExampleWithBLOBs(fintechDataAfuFruadExample);

            if (!list.isEmpty() && list.size() > 0) {
                String result = list.get(0).getData();
                log.error("afu:========+++++={}", result);
                if (null != result) {
                    AfuAfruadDto temp = new Gson().fromJson(result, AfuAfruadDto.class);
                    user.setAfuAfruad(temp);
                }
            } else {
                log.error("afu:=========null");
            }

        } catch (Exception e) {
            log.error("afu:=========FintechDataAfuFruadExample false{}", e.getMessage());
            e.printStackTrace();
        }*/


//        Response checkPhone = booleRiskService.checkPhone(id); //运营商认证  通过不通过
//        Response checkBank = booleRiskService.checkBank(id);  //银行认证  通过不通过
//        Response   preRisk=  booleRiskService.getProphetReport(id);//语言加报告 未知
//        Response  getPreRisk=booleRiskService.getPreRisk(id); //前置风险   未知
        return Response.success(user);
    }

    @Override
    public Response approval(@RequestBody UserApprovalVO vo) {
        FintechCredit credit = creditMapper.selectByPrimaryKey(vo.getUserKey());
        if (credit.getCreditStatus() != 0) {
            return Response.fail("已审批");
        }
        credit.setApproval(vo.getApproval());
        credit.setCreditStatus(vo.getStatus());
        credit.setFreezeAmount(0L);
        credit.setForzenAmount(0L);
        credit.setCreditAmount(vo.getCreditTotalAmt().longValue() * 100);
        credit.setUpdateTime(new Date());
        credit.setHandlerTime(new Date());
        creditMapper.updateByPrimaryKey(credit);

        //审批将实名信息通知商城模块
        FintechUserBaseInfo baseInfo = userBaseInfoDao.selectByPrimaryKey(vo.getUserKey());
        mallService.notifyUserApproval(baseInfo);
        return Response.success("审批成功");
    }

}
